# _*_ coding: utf-8 _*_
# @Time : 2024-01-18 22:36
# @Author : wf

# https://sc.chinaz.com/tupian/qinglvtupian.html
# https://sc.chinaz.com/tupian/qinglvtupian_2.html
# https://sc.chinaz.com/tupian/qinglvtupian_3.html

import urllib.request as request


def create_request(page):
    url_base = 'https://sc.chinaz.com/tupian/qinglvtupian'
    if page == 1:
        url = url_base + ".html"
    else:
        url = url_base + "_" + str(page) + ".html"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}

    return request.Request(url, headers=headers)


def get_content(req):
    return request.urlopen(req).read().decode('utf-8')


def download_img(content):
    from lxml import etree

    tree: etree._ElementTree = etree.HTML(content)
    src_list = tree.xpath('//div[@class="tupian-list com-img-txt-list"]//img/@data-original')
    name_list = tree.xpath('//div[@class="tupian-list com-img-txt-list"]//img/@alt')
    # print(len(src_list))
    # print(len(name_list))
    # for src in src_list:
    #     print(src)
    # for name in name_list:
    #     print(name)

    for i in range(len(src_list)):
        name = name_list[i]
        url = "https:" + src_list[i]
        file_name = "./img/" + name + ".jpg"
        request.urlretrieve(url, file_name)


if __name__ == '__main__':
    start_page = int(input("开始页数："))
    end_page = int(input("结束页数："))

    for page in range(start_page, end_page + 1):
        req = create_request(page)

        content = get_content(req)
        # print(content)
        download_img(content)

